package com.tx.admin.core.repository;

import java.util.List;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;

import org.hibernate.query.criteria.internal.OrderImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

import com.tx.admin.core.po.PagePo;
import com.tx.admin.util.common.JpaUtil;

@NoRepositoryBean
public interface SuperRepository <E> extends JpaRepository<E, String> ,JpaSpecificationExecutor<E> {

	long countById(String id);
	
	default long count(PagePo<E> params) {
		Specification<E> sp =( root, query,  cb) ->{
			// TODO Auto-generated method stub
			Predicate predicate = JpaUtil.buildSql(params.getEntity(), root, query, cb);
	
			return predicate;
		};
		return this.count(sp);
	}
	
	default Page<E> page(PagePo<E> params){
		Pageable pageable =PageRequest.of(params.getPageNumber() - 1, params.getPageSize());
		 
		Specification<E> sp =( root, query,  cb) ->{
			// TODO Auto-generated method stub
			Predicate predicate = JpaUtil.buildSql(params.getEntity(), root, query, cb);
			Order order= new OrderImpl(root.get(params.getOrderBy()),params.isAsc());
		
			query.orderBy(order);
			return predicate;
		};
		
		return this.findAll(sp, pageable);
	}
	
	/**
	 * 查询所有满足条件的数据
	 * @param params
	 * @return
	 */
	default List<E> findAll(E params){

		Specification<E> sp =( root, query,  cb) ->{
			// TODO Auto-generated method stub
			Predicate predicate = JpaUtil.buildSql(params, root, query, cb);
			return predicate;
		};
		
		return this.findAll(sp);
	}
	

}
